package com.controller;


import com.entity.Cart;
import com.entity.Commodity;
import com.entity.TbOrder;
import com.entity.TbOrderItem;
import com.service.CartService;
import com.service.CommodityService;
import com.service.OrderService;
import com.util.StatusCode;
import com.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  订单控制器
 * </p>
 *
 * @author sgx
 */
@Controller
@Api(value = "订单管理",tags = "订单模块")
public class OrdersController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private CommodityService commodityService;
    /**
     * 难点；如何接收前端传过来的数组，将其拆分得到每一件商品id
     * 在用商品id获取商品信息；放到Map集合对应其数量
     * @param session
     * @param goods
     * @return
     */

    @ResponseBody
    @ApiOperation("跳转支付")
    @RequestMapping(value = "/topay",method = RequestMethod.POST)
    public ResultVo toGet(HttpSession session,@RequestBody List<GoodsVO> goods, RedirectAttributes mv, Model model,
                          HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        String uId = (String) session.getAttribute("userid");
        if(uId.isEmpty()){
            return new ResultVo(true, StatusCode.OK,"请登录后操作");
        }
        //需要选中的商品信息，可能有多个；还有它的数量；放到一个数组里面
        Map<Commodity,String> goodsMap =  orderService.getGoodsMap(goods);
        session.setAttribute("goodsMap", goodsMap);
        if(goodsMap.isEmpty()){
            mv.addFlashAttribute("msg","未选择");
            model.addAttribute("1","1");
        }
        return new ResultVo(true, StatusCode.OK,"跳转到支付页");
    }


    /**
     * 订单实现思路：
     * 用户登录系统后将购物车放入redis供后续下单使用；
     * 用户点击提交订单生成订单表，在生成订单详细表；
     * 便利购物车进行价格比对，以数据库中的价格为准；同时拿到商品数量
     *
     */
    @PostMapping("creat_order")
    @ApiOperation("创建订单")
    @ResponseBody
    public ResultVo addOrder(@RequestBody TbOrder order,HttpSession session){
        String username = (String) session.getAttribute("username");
        order.setUsername(username);
        //立即购买的逻辑处理
        String id = null;
        try {
            id = order.getCommodityids().size() == 1 ? orderService.addOrder(order, true) : orderService.addOrder(order, false);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultVo(false,StatusCode.ERROR,"订单创建失败，库存不足");
        }
        session.setAttribute("order_id",id);
        /**
         * 订单创建成功后将商品下架
         */
        return new ResultVo(true,StatusCode.OK,"订单创建成功");
    }

    /**
     * 分页暂时订单列表
     * @param limit
     * @param page
     * @param session
     * @return
     */
    @ResponseBody
    @ApiOperation("")
    @GetMapping("/user/order/queryall")
    public LayuiPageVo userCart(int limit, int page, HttpSession session) {
        String couserid = (String) session.getAttribute("userid");
        String username = (String) session.getAttribute("username");
        List<TbOrderResDTO> list = orderService.queryAllOrders((page - 1) * limit, limit, username, CartController.CART_KEY);
        Integer dataNumber = list.size();
        return new LayuiPageVo("",0,dataNumber,list);
    }

    /**
     * 查询订单详细
     */
    @GetMapping("/user/order/detail/{id}")
    public String getOrderDetails(@PathVariable("id") String id, HttpSession session, Model mv){

        TbOrder tbOrder = orderService.queryOrderById(id);

        List<TbOrderItem> tbOrderItem = orderService.getOrderDetail(id);
        mv.addAttribute("order",tbOrder);
        mv.addAttribute("details", tbOrderItem);
        return "user/orders/orderdetails";
    }

    @PutMapping("/user/order/delete/{id}")
    @ResponseBody
    public ResultVo delete(@PathVariable("id") String id, HttpSession session, Model mv){
        int i = orderService.deleteOrder(id);
        if (i == 1){
            return new ResultVo(true,StatusCode.OK,"操作成功");
        }
        return new ResultVo(false,StatusCode.ERROR,"操作失败");
    }
}

